package com.spring.mybatis.conf;

import com.spring.mybatis.core.MapperScan;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @author yangjian
 */
@ComponentScan("com.spring.mybatis")
@MapperScan("com.spring.mybatis.mapper")
public class AppConfig {

	@Bean
	public SqlSessionFactory sessionFactory(DataSource dataSource) {
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("development", transactionFactory, dataSource);
		Configuration configuration = new Configuration(environment);
		return new SqlSessionFactoryBuilder().build(configuration);
	}

	@Bean
	public DataSource dataSource(MybatisConfig config) {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setUrl(config.getUrl());
		dataSource.setUsername(config.getUsername());
		dataSource.setPassword(config.getPassword());
		return dataSource;
	}
}
